/* $RCSFile: CrmEntityManager.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmEntityManager/CrmEntityManager.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:19  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:48  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Settings;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Configuration.Settings;
using AddonNice.Core;
using AddonNice.CRMWrapper;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CrmEntityManager
{

    /// <summary>
    /// Initializer for CrmEntityManager 
    /// </summary>
    public class CrmEntityManagerSI : CrmEntityManagerBaseSI
    {
        public CrmEntityManagerSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( CrmEntityManTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmEntityManagerSI Ctor BEG.",CrmEntityManTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( CrmEntityManTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmEntityManagerSI Ctor END.",CrmEntityManTrace.Sw.Info);
        }

        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( CrmEntityManTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmEntityManagerSI InitSettings BEG.",CrmEntityManTrace.Sw.Info);
            base.InitSettings(bSettings,pm);


            if ( CrmEntityManTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmEntityManagerInitializer Ctor END.",CrmEntityManTrace.Sw.Info);
        }
    }

    /// <summary>
    /// Input Rating about an Item
    /// </summary>
    public partial class CrmEntityManager : PortalCRMModuleControl 
    {
		CrmDB CrmManDB      =   new CrmDB();

		#region General Implementation

        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

		public override Guid GuidID 
		{
			get
			{
				return new Guid("{8EB9E53A-B98F-400f-B200-B95D28C761D4}");
			}
		}

        public override ModuleDevVersion ModuleVersion
        {
            get
            {
                return new ModuleDevVersion(){Major=1, Minor=0,Comment="First CrmEntityManager Version 01/01/2010"};
            }
        }

        public override bool AdminModule
        {
            get
            {
                return true;
            }
        }


		#endregion

        /// <summary>
        /// Public constructor. Sets base settings for module.
        /// </summary>
        public CrmEntityManager() 
        {
            if ( CrmEntityManTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmEntityManager Ctor END.",CrmEntityManTrace.Sw.Info);
        }

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmEntityManagerSI(bSettings,this);
        }


        /// <summary>
        /// The Page_Load event handler on this User Control is used to
        /// obtain a DataSet of announcement information from the CrmEntityManager
        /// table, and then databind the results to a templated DataList
        /// server control.  It uses the AddonNice.CrmEntityManagerDB()
        /// data component to encapsulate all data functionality. 
        /// </summary>
        protected void Page_Load(object sender, System.EventArgs e) 
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager Page_Load Time: {0}, IsPostBack: {1}",DateTime.UtcNow,IsPostBack),CrmEntityManTrace.Sw.Info);
            if ( !IsPostBack )
            {
            }
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager Page_Load END.",CrmEntityManTrace.Sw.Info);
        }

        void RadGrid1_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid1_NeedDataSource BEG Reason: {0}.",e.RebindReason),CrmEntityManTrace.Sw.Info);
            try
            {
                DataTable Tb        =   CrmManDB.GetAllCrmEntityTb();
                RadGrid1.DataSource =   Tb;
            }
            catch ( Exception ex )
            {
			    if (CrmEntityManTrace.Sw.TraceError)
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid1_NeedDataSource ex: {0}.",ex),CrmEntityManTrace.Sw.Info);
                throw;
            }
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid1_NeedDataSource END.",CrmEntityManTrace.Sw.Info);
        }

        void RadGrid2_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_NeedDataSource BEG Reason: {0}.",e.RebindReason),CrmEntityManTrace.Sw.Info);
            try
            {
                int CrmEntityId        =   (RadGrid1.SelectedValue == null ) ? -1:(int)RadGrid1.SelectedValue;
                RadGrid2.DataSource =   CrmManDB.GetModulesByEntityTb(CrmEntityId);
            }
            catch ( Exception ex )
            {
			    if (CrmEntityManTrace.Sw.TraceError)
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid2_NeedDataSource ex: {0}.",ex),CrmEntityManTrace.Sw.Info);
                throw;
            }
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid2_NeedDataSource END .",CrmEntityManTrace.Sw.Info);
        }

        void RadGrid3_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid3_NeedDataSource BEG Reason: {0}.",e.RebindReason),CrmEntityManTrace.Sw.Info);
            try
            {
                int CrmEntityId        =   (RadGrid1.SelectedValue == null ) ? -1:(int)RadGrid1.SelectedValue;
                RadGrid3.DataSource =   CrmManDB.GetCrmServersByEntityTb(CrmEntityId);
            }
            catch ( Exception ex )
            {
			    if (CrmEntityManTrace.Sw.TraceError)
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid3_NeedDataSource ex: {0}.",ex),CrmEntityManTrace.Sw.Info);
                throw;
            }
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid3_NeedDataSource END .",CrmEntityManTrace.Sw.Info);
        }

        #region RadGrid1 for Crm Entities

        void RadGrid1_SelectedIndexChanged(object sender,EventArgs e)
        {
            bool hasSel                                             =   RadGrid1.SelectedValue != null ;
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid1_SelectedIndexChanged BEG hasSel: {0}.",hasSel),CrmEntityManTrace.Sw.Info);
            if ( !hasSel  )
            {
                RadGrid2.MasterTableView.CommandItemDisplay         =   GridCommandItemDisplay.None;
                RadGrid3.MasterTableView.CommandItemDisplay         =   GridCommandItemDisplay.None;
            }
            else
            {
                int CrmEntityId                                     =   (int)RadGrid1.SelectedValue;
                RefreshCommands(CrmEntityId);
            }
            RadGrid2.Rebind();
            RadGrid3.Rebind();
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid1_SelectedIndexChanged END.",CrmEntityManTrace.Sw.Info);
        }


        void RefreshCommands(int CrmEntityId)
        {
            int CountOther                                      =   0;
            int Count                                           =   CrmManDB.ExistModulesByCrmEntity(CrmEntityId,ref CountOther);
            if ( CountOther > 0 ) // No more new entities, not necessary to offered adding 
                    RadGrid2.MasterTableView.CommandItemDisplay =   GridCommandItemDisplay.Top;
            else    RadGrid2.MasterTableView.CommandItemDisplay =   GridCommandItemDisplay.None;
            CountOther                                          =   0;
            Count                                               =   CrmManDB.ExistCrmServerByCrmEntity(CrmEntityId,ref CountOther);
            if ( (CountOther > 0) || ( Count > 0)) // No more new entities, not necessary to offered adding 
                    RadGrid3.MasterTableView.CommandItemDisplay =   GridCommandItemDisplay.Top;
            else    RadGrid3.MasterTableView.CommandItemDisplay =   GridCommandItemDisplay.None;
        }

        void RadGrid1_DataBound(object sender,EventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid1_DataBound BEG RadGrid1.Items.Count: {0}",RadGrid1.Items.Count),CrmEntityManTrace.Sw.Info);
            if ( RadGrid1.Items.Count > 0 )
            {
                if ( RadGrid1.SelectedValue == null )
                    RadGrid1.Items[0].Selected                      =   true;
                int CrmEntityId                                     =   (int)RadGrid1.SelectedValue;
                RefreshCommands(CrmEntityId);
            }
            else
            {
                RadGrid2.MasterTableView.CommandItemDisplay         =   GridCommandItemDisplay.None;
                RadGrid3.MasterTableView.CommandItemDisplay         =   GridCommandItemDisplay.None;
            }
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid1_DataBound END.",CrmEntityManTrace.Sw.Info);
        }

        void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid1_UpdateCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),CrmEntityManTrace.Sw.Info);
            GridEditableItem editedItem                     =   e.Item as GridEditableItem;
            Hashtable newValues                             =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
            try
            {
                int CrmEntityId             =   (int)(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][ "EntityId"]);
                string SchemaName           =   (string)newValues["SchemaName"];
                string EntityVersion        =   (string)newValues["EntityVersion"];
                string FriendlyName         =   (string)newValues["Friendlyname"];
                string InitClass            =   (string)newValues["InitClass"];
                string LoadAssembly         =   (string)newValues["LoadAssembly"];
                string PackageName          =   (string)newValues["PackageName"];

                bool NeedCreateBuilder      =   bool.Parse(newValues["NeedCreateBuilder"].ToString());
                bool NeedUpdateBuilder      =   bool.Parse(newValues["NeedUpdateBuilder"].ToString());
                bool NeedUIBuilder          =   bool.Parse(newValues["NeedUIBuilder"].ToString());

                CrmManDB.UpdateCrmEntity(CrmEntityId,SchemaName,EntityVersion,FriendlyName,InitClass,LoadAssembly,PackageName,NeedCreateBuilder,NeedUpdateBuilder,NeedUIBuilder);
		        if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid1_UpdateCommand END CrmEntityId: {0}, FriendlyName: {1}",CrmEntityId,FriendlyName),CrmEntityManTrace.Sw.Info);
            }
            catch (Exception ex)
            {
			    if (CrmEntityManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid1_UpdateCommand ex: {0}",ex),CrmEntityManTrace.Sw.Info);
                throw;
            }
            return;
        }

        private void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid1_InsertCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),CrmEntityManTrace.Sw.Info);
            GridEditableItem Item           =   e.Item as GridEditableItem;

            Hashtable newValues             =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, Item);

            try
            {
                string SchemaName           =   (string)newValues["SchemaName"];
                string EntityVersion        =   (string)newValues["EntityVersion"];
                string FriendlyName         =   (string)newValues["Friendlyname"];
                string InitClass            =   (string)newValues["InitClass"];
                string LoadAssembly         =   (string)newValues["LoadAssembly"];
                string PackageName          =   (string)newValues["PackageName"];
                bool NeedCreateBuilder      =   bool.Parse(newValues["NeedCreateBuilder"].ToString());
                bool NeedUpdateBuilder      =   bool.Parse(newValues["NeedUpdateBuilder"].ToString());
                bool NeedUIBuilder          =   bool.Parse(newValues["NeedUIBuilder"].ToString());

                int CrmEntityId             =   CrmManDB.AddCrmEntity(SchemaName,EntityVersion,FriendlyName,InitClass,LoadAssembly,PackageName,NeedCreateBuilder,NeedUpdateBuilder,NeedUIBuilder);
		        if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid1_InsertCommand END CrmEntityId: {0}, FriendlyName: {1}",CrmEntityId,FriendlyName),CrmEntityManTrace.Sw.Info);
            }
            catch (Exception ex)
            {
				if (CrmEntityManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid1_InsertCommand ex: {0}",ex),CrmEntityManTrace.Sw.Info);
                throw;
            }
        }
        
        void RadGrid1_DeleteCommand(object source,GridCommandEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid1_DeleteCommand BEG.",CrmEntityManTrace.Sw.Info);
            GridEditableItem Item           =   e.Item as GridEditableItem;

            try
            {
                int CrmEntityId             =   (int)(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][ "EntityId"]); 
                CrmManDB.DeleteCrmServer(CrmEntityId);
		        if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid1_DeleteCommand END CrmEntityId: {0}.",CrmEntityId),CrmEntityManTrace.Sw.Info);
            }
            catch (Exception ex)
            {
				if (CrmEntityManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid1_InsertCommand ex: {0}",ex),CrmEntityManTrace.Sw.Info);
                throw;
            }
        }
        
        #endregion RadGrid1 for Crm Entities

        #region RadGrid2 for Related General Modules definitions

        void RadGrid2_DataBound(object sender,EventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_DataBound BEG RadGrid2.Items.Count: {0}",RadGrid2.Items.Count),CrmEntityManTrace.Sw.Info);
            if ( RadGrid2.Items.Count > 0 )
            {
                if ( RadGrid2.SelectedValue == null )
                    RadGrid2.Items[0].Selected                      =   true;
            }
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid2_DataBound END.",CrmEntityManTrace.Sw.Info);
        }

        void RadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_ItemDataBound BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),CrmEntityManTrace.Sw.Info);
            if ( !( e.Item is GridEditableItem ) )
                return;
            GridEditableItem Item                           =   e.Item as GridEditableItem;
		    if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_ItemDataBound Item.IsInEditMode: {0}",Item.IsInEditMode),CrmEntityManTrace.Sw.Info);
            if (Item.IsInEditMode)
            {
                DataRowView rw                              =   null;
                if ( !Item.OwnerTableView.IsItemInserted )
                    rw                                      =   (DataRowView)e.Item.DataItem;
                GridEditManager editMan                     =   Item.EditManager;

                GridDropDownListColumnEditor editor         =   (GridDropDownListColumnEditor)editMan.GetColumnEditor( "ModuleDefId" );
                // We display friendyName
                SqlDataReader rd                            =   null;
                try
                {
                    rd                                      =   new ModulesDB().GetModuleDefinitions();
                    editor.DataSource                       =   rd;
                    editor.DataBind();
                    if (rw != null)
                    {
                        RadComboBoxItem it                  =   editor.ComboBoxControl.Items.FindItemByValue(rw["ModuleDefId"].ToString());
                        if (it != null)
                            it.Selected                     =   true;
                    }
                }
                catch ( Exception ex )
                {
				    if (CrmEntityManTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid2_ItemDataBound ex: {0}",ex),CrmEntityManTrace.Sw.Info);
                    throw;
                }
                finally
                {
                    if ( rd != null )
                        rd.Close();
                }
            }
            else
            {
                DataRowView rw                              =   (DataRowView)e.Item.DataItem;
                string val                                  =   rw["ModuleDefId"].ToString();
                if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_ItemDataBound val: {0}",val),CrmEntityManTrace.Sw.Info);
                Item["ModuleDefId"].Text                    =   val;
                Label Lbl                                   =   (Label)e.Item.FindControl("LblType");
                if ( Lbl != null )
                {
                    string sType                            =   Lbl.Text;
                    VersionType pType                       =   (VersionType)int.Parse(sType);
                    if (CrmEntityManTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_ItemDataBound pType: {0}", pType), CrmEntityManTrace.Sw.Info);
                    Lbl.Text                                =   pType.ToString();
                }
            }
        }

        private void RadGrid2_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid2_InsertCommand BEG.",CrmEntityManTrace.Sw.Info);
            GridEditableItem Item       =   e.Item as GridEditableItem;
            if ( RadGrid1.SelectedValue == null )
            {
			    if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]CrmEntityManager RadGrid2_InsertCommand END No EntityID cancelling.",CrmEntityManTrace.Sw.Info);
                e.Canceled              =   true;
                return;
            }

            int CrmEntityId                =   (int)RadGrid1.SelectedValue;
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_InsertCommand CrmEntityId: {0}",CrmEntityId),CrmEntityManTrace.Sw.Info);
            Hashtable newValues         =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, Item);

            try
            {
                Guid newModuleDefId     =   new Guid(newValues["ModuleDefId"].ToString()); // yes it is the Guid value from the RadComboBox
			    if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_InsertCommand newModuleDefId: {0}",newModuleDefId),CrmEntityManTrace.Sw.Info);
                CrmManDB.AddModuleEntity(CrmEntityId,newModuleDefId);
			    if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_InsertCommand END CrmEntityId: {0}, newModuleDefId: {1}",CrmEntityId,newModuleDefId),CrmEntityManTrace.Sw.Info);
                RefreshCommands(CrmEntityId);
            }
            catch (Exception ex)
            {
				if (CrmEntityManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid2_InsertCommand ex: {0}",ex),CrmEntityManTrace.Sw.Info);
                throw;
            }
        }
        
        
        void RadGrid2_DeleteCommand(object source,GridCommandEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid2_DeleteCommand BEG.",CrmEntityManTrace.Sw.Info);
            GridEditableItem Item       =   e.Item as GridEditableItem;

            int CrmEntityId                =   (int)(Item.OwnerTableView.DataKeyValues[Item.ItemIndex][ "EntityId"]);
            Guid ModuleDefId            =   (Guid)(Item.OwnerTableView.DataKeyValues[Item.ItemIndex][ "ModuleDefId"]);
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_DeleteCommand CrmEntityId: {0}, PortalID: {1}",CrmEntityId,PortalID),CrmEntityManTrace.Sw.Info);
            try
            {
                CrmManDB.DeleteModuleEntity(CrmEntityId,ModuleDefId);
                RefreshCommands(CrmEntityId);
            }
            catch (Exception ex)
            {
				if (CrmEntityManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid2_DeleteCommand ex: {0}",ex),CrmEntityManTrace.Sw.Info);
                throw;
            }
        }

        
        #endregion RadGrid2 for Related General Modules definitions
        
        #region RadGrid3 for Related Crm Servers

        void RadGrid3_DataBound(object sender,EventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid3_DataBound BEG RadGrid3.Items.Count: {0}",RadGrid3.Items.Count),CrmEntityManTrace.Sw.Info);
            if ( RadGrid3.Items.Count > 0 )
            {
                if ( RadGrid3.SelectedValue == null )
                    RadGrid3.Items[0].Selected                      =   true;
            }
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid3_DataBound END.",CrmEntityManTrace.Sw.Info);
        }

        void RadGrid3_ItemDataBound(object sender, GridItemEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid3_ItemDataBound BEG.",CrmEntityManTrace.Sw.Info);
            if ( !( e.Item is GridEditableItem ) )
                return;
            GridEditableItem Item                           =   e.Item as GridEditableItem;
		    if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid3_ItemDataBound Item.IsInEditMode: {0}",Item.IsInEditMode),CrmEntityManTrace.Sw.Info);
            if (Item.IsInEditMode)
            {
                DataRowView rw                              =   null;
                if ( !Item.OwnerTableView.IsItemInserted )
                    rw                                      =   (DataRowView)e.Item.DataItem;
                GridEditManager editMan                     =   Item.EditManager;

                GridDropDownListColumnEditor editor         =   (GridDropDownListColumnEditor)editMan.GetColumnEditor( "CrmServer" );
                //in case you have RadComboBox editor for the GridDropDownColumn (this is the default editor),         
                //you will need to use ComboBoxControl below instead of DropDownListControl
                //Then you can modify the list control as per your custom conventions
                try
                {
                    DataTable Tb                            =   CrmManDB.GetAllCrmServerTb();
                    Tb.Columns.Add("CrmServer",typeof(string));
                    foreach ( DataRow vrw in Tb.Rows )
                    {
                        vrw["CrmServer"]                    =   string.Format("{0}/{1}",vrw["DiscoServer"],vrw["Organization"]);
                    }
                    editor.DataSource                       =   Tb;
                    editor.DataBind();
                    if (rw != null)
                    {
                        RadComboBoxItem it                  =   editor.ComboBoxControl.Items.FindItemByValue(rw["CrmServerId"].ToString());
                        if (it != null)
                            it.Selected                     =   true;
                    }
                }
                catch ( Exception ex )
                {
				    if (CrmEntityManTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid3_ItemDataBound ex: {0}",ex),CrmEntityManTrace.Sw.Info);
                    throw;
                }
            }
            else
            {
                DataRowView rw                              =   (DataRowView)e.Item.DataItem;
                string val                                  =   rw["CrmServerId"].ToString();
                if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid3_ItemDataBound val: {0}",val),CrmEntityManTrace.Sw.Info);
                Item["CrmServer"].Text                      =   val;
            }

        }

        private void RadGrid3_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid3_InsertCommand BEG OwnerTableView.Name: {0}",e.Item.OwnerTableView.Name),CrmEntityManTrace.Sw.Info);
            GridEditableItem Item       =   e.Item as GridEditableItem;

            if ( RadGrid1.SelectedValue == null )
            {
			    if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine("[V]CrmEntityManager RadGrid3_InsertCommand END No EntityID cancelling.",CrmEntityManTrace.Sw.Info);
                e.Canceled              =   true;
                return;
            }

            int CrmEntityId             =   (int)RadGrid1.SelectedValue;
            DBCrmEntity OEntity         =   CrmManDB.GetCrmEntityObj(CrmEntityId);
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid3_InsertCommand CrmEntityId: {0}",CrmEntityId),CrmEntityManTrace.Sw.Info);
            Hashtable newValues         =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, Item);

            try
            {
                int CrmServerId         =   int.Parse(newValues["CrmServerId"].ToString()); // yes it is the int value from the RadComboBox
			    if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid3_InsertCommand CrmServerId: {0}",CrmServerId),CrmEntityManTrace.Sw.Info);
                CrmManDB.AddCrmServerEntity(CrmEntityId,CrmServerId,OEntity.EntityVersion);
                RefreshCommands(CrmEntityId);
			    if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid3_InsertCommand END CrmEntityId: {0}, CrmServerId: {1}",CrmEntityId,CrmServerId),CrmEntityManTrace.Sw.Info);
            }
            catch (Exception ex)
            {
				if (CrmEntityManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid3_InsertCommand ex: {0}",ex),CrmEntityManTrace.Sw.Info);
                throw;
            }
        }
        
        void RadGrid3_DeleteCommand(object source,GridCommandEventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid3_DeleteCommand BEG.",CrmEntityManTrace.Sw.Info);
            GridEditableItem Item       =   e.Item as GridEditableItem;

            int CrmEntityId                =   (int)(Item.OwnerTableView.DataKeyValues[Item.ItemIndex][ "EntityId"]);
            int CrmServerId             =   (int)(Item.OwnerTableView.DataKeyValues[Item.ItemIndex][ "CrmServerId"]);
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid3_DeleteCommand CrmEntityId: {0}, CrmServerId: {1}",CrmEntityId,CrmServerId),CrmEntityManTrace.Sw.Info);
            try
            {
                CrmManDB.DeleteCrmServerEntity(CrmEntityId,CrmServerId);
                RefreshCommands(CrmEntityId);
            }
            catch (Exception ex)
            {
				if (CrmEntityManTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmEntityManager RadGrid3_DeleteCommand ex: {0}",ex),CrmEntityManTrace.Sw.Info);
                throw;
            }
        }

        void RadGrid3_ItemCommand(object source,GridCommandEventArgs e)
        {
	        if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid2_ItemCommand BEG CommandName: {0}.",e.CommandName),CrmEntityManTrace.Sw.Info);
            if ( e.CommandName == "UpdateEntity" )
            {
                int CrmServerId     =   (RadGrid3.SelectedValue == null ) ? -1:(int)RadGrid3.SelectedValue;
                int CrmEntityId     =   (RadGrid1.SelectedValue == null ) ? -1:(int)RadGrid1.SelectedValue;
                if (CrmEntityManTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmEntityManager RadGrid3_ItemCommand CrmServerId: {0}.",CrmServerId),CrmEntityManTrace.Sw.Info);
                if ( ( CrmServerId != -1 ) && ( CrmEntityId != -1 ) )
                {
                    string Url      =   Config.ModulesPath+"/CrmServerManager/UpdateCrmEntity.aspx";
                    Url             =   HttpUrlBuilder.BuildUrlWithCustomAttributes(Url, PageID,string.Format("mId={0}&crmserverid={1}&crmentityid={2}",ModuleID,CrmServerId,CrmEntityId));
                    ADNPage.Redirect(Url,true);
                }
            }
			if (CrmEntityManTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager RadGrid3_ItemCommand END.",CrmEntityManTrace.Sw.Info);
        }

        #endregion RadGrid for Related crm Servers

        #region Std Overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
			if (CrmEntityManTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager Page_PreInit BEG.",(CrmEntityManTrace.Sw.TraceVerbose) ? CrmEntityManTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            base.Page_PreInit(sender, e);
			if (CrmEntityManTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmEntityManager Page_PreInit END.",(CrmEntityManTrace.Sw.TraceVerbose) ? CrmEntityManTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }
        
        override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

        private void InitializeComponent() 
        {
			Load                        +=  new EventHandler(Page_Load);
            
            RadGrid1.NeedDataSource     +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            //RadGrid1.ItemDataBound      +=  new GridItemEventHandler(RadGrid1_ItemDataBound);
            RadGrid1.DeleteCommand      +=  new GridCommandEventHandler(RadGrid1_DeleteCommand);
            RadGrid1.InsertCommand      +=  new GridCommandEventHandler(RadGrid1_InsertCommand);
            RadGrid1.UpdateCommand      +=  new GridCommandEventHandler(RadGrid1_UpdateCommand);
            RadGrid1.SelectedIndexChanged += new EventHandler(RadGrid1_SelectedIndexChanged);
            RadGrid1.DataBound          +=  new EventHandler(RadGrid1_DataBound);
            
            RadGrid2.NeedDataSource     +=  new GridNeedDataSourceEventHandler(RadGrid2_NeedDataSource);
            RadGrid2.ItemDataBound      +=  new GridItemEventHandler(RadGrid2_ItemDataBound);
            RadGrid2.InsertCommand      +=  new GridCommandEventHandler(RadGrid2_InsertCommand);
            RadGrid2.DeleteCommand      +=  new GridCommandEventHandler(RadGrid2_DeleteCommand);
            RadGrid2.DataBound          +=  new EventHandler(RadGrid2_DataBound);
            
            RadGrid3.NeedDataSource     +=  new GridNeedDataSourceEventHandler(RadGrid3_NeedDataSource);
            RadGrid3.ItemDataBound      +=  new GridItemEventHandler(RadGrid3_ItemDataBound);
            RadGrid3.DeleteCommand      +=  new GridCommandEventHandler(RadGrid3_DeleteCommand);
            RadGrid3.InsertCommand      +=  new GridCommandEventHandler(RadGrid3_InsertCommand);
            RadGrid3.DataBound          +=  new EventHandler(RadGrid3_DataBound);
            RadGrid3.ItemCommand        +=  new GridCommandEventHandler(RadGrid3_ItemCommand);
		}

		#endregion
    }
}
